package pay.serviceImpl.sys.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import pay.common.Constant;
import pay.common.ConstantFYJZH;
import pay.common.ConstantUser;
import pay.common.HqlFilter;
import pay.entity.SysUser;
import pay.service.sys.ISysUser;
import pay.serviceImpl.dao.base.impl.BaseServiceImpl;
import pay.utils.DateUtil;
import pay.utils.FYApiUtil;
import pay.utils.LongId;
import pay.utils.MapSortUtil;
import pay.utils.StringHelper;
import pay.utils.XmlUtils;

@Service
public class SysUserImpl extends BaseServiceImpl<SysUser> implements ISysUser {

	private Logger logger = LoggerFactory.getLogger(SysUserImpl.class);

	 /**
     * 金账户baseURl，从配置文件中读取
     */
    @Value("${fy.goldAccount.baseUrl}")
    private String jzhBaseUrl;
    @Value("${fy.mchntCd}")
    private String mchnt_cd;
    @Value("${fy.goldAccount.pathBaseUrl}")
    private String pathBaseUrl;
    
	@Resource
	private JdbcTemplate jdbcTemplate;

	@Override
	public SysUser findById(Long id) {
		if (id == null) {
			return null;
		}

		// 如果id 大于14位则只取14位
		//id = checkId(id);

		return this.getById(id);
	}

	@Override
	public String getNameById(Long id) {
		String str = null;
		SysUser user = findById(id);
		if (user != null) {
			str = user.getRealName();
		}
		return str;
	}

	@Override
	public Long add(SysUser o) {
		Long id = LongId.get();
		o.setId(id);
		o.setRegistCts(System.currentTimeMillis());
		super.save(o);
		return id;
	}

	@Override
	public SysUser getByAccount(String account) {
		if (StringHelper.isEmpty(account)) {
			return null;
		} else {
			HqlFilter hqlFilter = new HqlFilter();
			hqlFilter.addEQFilter("name", account);
			return getByFilter(hqlFilter);
		}

	}

	@Override
	public SysUser getByAccountId(String accountId) {
		if (StringHelper.isEmpty(accountId)) {
			return null;
		} else {
			HqlFilter hqlFilter = new HqlFilter();
			hqlFilter.addEQFilter("accountId", accountId);
			return getByFilter(hqlFilter);
		}

	}

	@Override
	public SysUser getByMobileId(String mobileId) {
		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("mobileId", mobileId);
		return getByFilter(hqlFilter);
	}

	/**
	 *根据手机号获取用户
	 * @param phoneNum
	 * @return
	 */
	@Override
	public SysUser getByPhoneNum(String phoneNum) {
		return getByPhoneNum(phoneNum, ConstantUser.NOT_CLOSE_ACCOUNT);
	}

	/**
	 * 根据手机号和销户状态获取用户
	 * @param phoneNum
	 * @param closeAccount 销户状态（0：末销户，1：已销户）
	 * @return
	 */
	@Override
	public SysUser getByPhoneNum(String phoneNum, Integer closeAccount){
		SysUser user = null;
		if(StringHelper.isBlank(phoneNum)){
			return user;
		}

		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("name", phoneNum);
		if( closeAccount != null){
			hqlFilter.addEQFilter("closeAccount",closeAccount);
		}
		user = getByFilter(hqlFilter);
		return user;
	}

	// 根据用户id ,获取理财师id
	@Override
	public Long getFinUserIdByUserId(Long userId) {
		Long finUserId = null;
		SysUser user = findById(userId);
		if (user != null && StringHelper.isNotEmpty(user.getRecommendCode())) {
			SysUser finUser = getByPhoneNum(user.getRecommendCode());
			if (finUser != null) {
				finUserId = finUser.getId();
			}
		}
		return finUserId;
	}

	@Override
	public SysUser delete(Long id) {
		SysUser sysUser = new SysUser();

		// 如果id 大于14位则只取14位
		//id = checkId(id);

		sysUser.setId(id);
		super.delete(sysUser);
		return sysUser;
	}

	@Override
	public boolean existById(Long id) {
		// TODO Auto-generated method stub
		SysUser sysUser = findById(id);
		return sysUser != null ? true : false;
	}

	@Override
	public boolean existByName(String name) {
		// TODO Auto-generated method stub
		SysUser sysUser = getByAccount(name);
		return sysUser != null ? true : false;
	}

	@Override
	public boolean existByMobileId(String mobileId) {
		// TODO Auto-generated method stub

		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("mobileId", mobileId);
		SysUser sysUser = getByFilter(hqlFilter);
		return sysUser != null ? true : false;
	}

	@Override
	public List<SysUser> getAll() {
		HqlFilter hqlFilter = new HqlFilter();
		return findByFilter(hqlFilter);
	}

	@Override
	public Long checkId(Long id) {
		Long newId = id;

		if (id != null && id.toString().length() > 14) {
			String idStr = id.toString();
			String newIdStr = idStr.substring(0, 14);
			newId = Long.valueOf(newIdStr);
		}
		return newId;
	}

	/**
	 * 设置用户的绑卡信息为已支付
	 */
	@Override
	public void upUserByPayment(Long userId, String accountId, String identity,
			String accountName,int hasVirtualAccount) {
		logger.info("upUserByPayment userId = " + userId + "  accountId = "
				+ accountId + "  identity = " + identity + "  accountName = "
				+ accountName);
		SysUser user = this.findById(userId);
		if (user != null) {
			user.setHasVirtualAccount(hasVirtualAccount);
			if (StringHelper.isNotEmpty(accountId)
					&& StringHelper.isEmpty(user.getAccountId())) {
				user.setAccountId(accountId);
			}

			if (StringHelper.isNotEmpty(identity)) {
				user.setIdentity(identity);
			}

			if (StringHelper.isNotEmpty(accountName)) {
				user.setRealName(accountName);
			}

			if (StringHelper.isEmpty(user.getPaymentNo())) {
				user.setPaymentNo("*********"); // 暂时兼容， 为了统计日报
			}

			user.setTieCard(Constant.USER_TIE_CARD_TRUE);

			logger.info("upUserByPayment will upd user ");
			update(user);
		}

	}

	@Override
	public SysUser getUserByRealName(String realName) {
		SysUser user = null;

		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("RealName", realName);
		List<SysUser> userList = this.findByFilter(hqlFilter);
		if (userList.size() > 0) {
			user = userList.get(0);
		}

		return user;
	}

	@Override
	public List<SysUser> getUserListByRealName(String realName) {

		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addLKFilter("RealName", realName);
		List<SysUser> userList = this.findByFilter(hqlFilter);

		return userList;
	}

	@Override
	public List<SysUser> getUserByRecommendCode(String recommendCode) {

		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("recommendCode", recommendCode);
		List<SysUser> userList = this.findByFilter(hqlFilter);

		return userList;
	}

	@Override
	public Integer getRelUserNumById(Long userId) {
		Integer size = 0;
		SysUser finUser = findById(userId);
		if (finUser != null) {
			String recommendCode = finUser.getName();

			String sql = "SELECT count(*) FROM hkServer.SysUser  where  recommendCode = "
					+ recommendCode;

			size = jdbcTemplate.queryForObject(sql, Integer.class);
		}

		return size;
	}

	@Override
	public BigDecimal getUserLeftMoney(SysUser user) {//余额以元为单位
		String userPhone=user.getName();
		BigDecimal leftMoney=BigDecimal.valueOf(0);                           
        try {        	        	
            String result = queryLeftMoney(userPhone);
            String resp_code = XmlUtils.getVal(result, "resp_code");
            if(ConstantFYJZH.FY_REQCODE_SUCC.equals(resp_code)) {//请求成功
				String ca_balance = XmlUtils.getVal(result, "ca_balance");//余额
				if (StringHelper.isEmpty(ca_balance)) {
					leftMoney = BigDecimal.valueOf(0.00);
				} else {
					leftMoney = BigDecimal.valueOf(Double.valueOf(ca_balance));
				}
			}
        } catch (Exception e) {
        	logger.info("查询金账户用户余额异常, userPhone={}",  userPhone);
            logger.error("---------------------------------error-----------------------------",  e);
        }           
        return leftMoney;
	}
    
    private String queryLeftMoney(String userPhone) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("mchnt_cd", mchnt_cd);
		Long cts = System.currentTimeMillis();
		String mchnt_txn_dt = DateUtil.longToShortDate02(cts);
		map.put("mchnt_txn_ssn", userPhone + cts);
		map.put("mchnt_txn_dt", mchnt_txn_dt);
		map.put("cust_no", userPhone);
		map = MapSortUtil.sortMapByKey(map);
		String pathUrl = pathBaseUrl + "/BalanceAction.action";
		return FYApiUtil.sendPostToFYUtils(map, jzhBaseUrl, pathUrl);
	}

}
